# 从flask包中导入Flask类
import json
from datetime import datetime

from flask import Flask, request, render_template, redirect, url_for, make_response, jsonify, session, current_app, g
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text

from blueprint.grade import grade_bp
from blueprint.student import student_bp
from blueprint.user import user_bp
from exts import db

# 使用Flask类创建app对象
app = Flask(__name__)
# __name__：模块或者包名称，这里是app.py模块名字
print('__name__', __name__)

# 设置秘钥
app.secret_key = '123@#$345'

# 读取配置文件
app.config.from_object('config')

app.register_blueprint(grade_bp)
# # 创建SQLAlchemy对象
# db = SQLAlchemy(app)

# sqlalchemy初始化
db.init_app(app)

# 实例化Migrate
migrate = Migrate(app, db)

with app.app_context():
    # 根据模型建表
    db.create_all()

# 注册模块蓝图
app.register_blueprint(student_bp)
app.register_blueprint(user_bp)

# 在应用上下文中使用current_app
with app.app_context():
    # 配置DEBUG模式
    app.config['DEBUG'] = True

    # 访问应用的配置
    debug_mode = current_app.config['DEBUG']
    print(f'DEBUG模式：{debug_mode}')


# 格式化日期
def date_format(value, format='%Y年%m月%d日'):
    return value.strftime(format)


# 添加自定义过滤器
app.add_template_filter(date_format, 'dateformat')


# 格式化日期
def date_format(value, format='%Y年%m月%d日'):
    return value.strftime(format)


# 添加自定义过滤器
app.add_template_filter(date_format, 'dateformat')


@app.before_request
def set_name():
    g.username = '老六'


@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!', 201


@app.route('/blog/list')
def blog_list():
    '''
    url带参数，示例url请示 http://127.0.0.1:5000/blog/list?page=2&size=10
    :return:
    '''
    page = request.args.get('page', default=1, type=int)
    size = request.args.get('size', default=10, type=int)
    print(page, size)
    return '博客列表'


@app.route('/blog/<int:id>')
def blog_detail(id):
    '''
    url变量 示例url请求 /blog/1
    :param id:
    :return:
    '''
    return f'博客id={id}的详细页面'


@app.route('/login', methods=['GET', 'POST'])
def login():
    '''
    用户登录
    :return:
    '''
    print(request.method)
    if request.method == 'GET':
        return render_template('login.html')
    else:
        username = request.values.get('username')
        password = request.values.get('password')
        print(username, password)
        return 'ok'


@app.route('/test_hook')
def test_hook():
    print('do something...')
    # a = 1 / 0
    return 'ok'


@app.before_request
def do_something_before():
    print('before_request', request.url)


@app.after_request
def do_something_after(response):
    print('after_request', request.url)
    return response


@app.teardown_request
def do_something_teardown(exception):
    print('teardown_request', exception, request.url)


@app.route('/python222')
def python222():
    return redirect(url_for('hello_world'))


@app.route('/plain')
def plain():
    response = make_response('<p>Hello,Python222!</p>')
    response.mimetype = 'text/plain'
    return response


@app.route('/html')
def html():
    response = make_response('<p>Hello python222!</p>')
    response.mimetype = 'text/html'
    return response


@app.route('/ajax')
def ajax():
    data = {
        'name': '小锋',
        'site': 'www.python222.com'
    }
    response = make_response(json.dumps(data))
    response.mimetype = 'application/json'
    return response


@app.route('/ajax2')
def ajax2():
    return jsonify(name='小锋2', size='www.python222.com')


@app.route('/cookie')
def set_cookie():
    response = make_response()
    response.set_cookie('username', 'jack')
    session['password'] = 123456
    return 'ok'


@app.route('/getcookie')
def get_cookie():
    return request.cookies.get('username')


@app.route('/getcookie2')
def get_cookie2():
    print('username', session['password'])
    return 'ok'


if __name__ == '__main__':
    app.run()
